import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';
/*
 *
 * getTemporaryDirectory 获取应用缓存目录，等同IOS的NSTemporaryDirectory和Android的getCacheDir方法
 *
 * getApplicationSupportDirectory 应用程序可以在其中放置应用程序支持文件的目录的路径
 *
 * getLibraryDirectory 应用程序可以在其中存储持久性文件，如sqlite）,在Android上，此函数抛出[UnsupportedError]异常，没有等效项路径存在
 *
 * getApplicationDocumentsDirectory 获取应用文件目录类似于Ios的NSDocumentDirectory和Android上的 AppData目录
 *
 * getExternalStorageDirectory 存储卡，仅在Android平台可以使用
 *
 */
class CacheUtil{
  ///获取文件夹缓存大小
  static Future<double> loadApplicationCache() async {
    //获取文件夹
    Directory docDirectory = await getApplicationDocumentsDirectory();
    Directory tempDirectory = await getTemporaryDirectory();

    double size = 0;

    if (docDirectory.existsSync()) {
      size += await getTotalSizeOfFilesInDir(docDirectory);
    }
    if (tempDirectory.existsSync()) {
      size += await getTotalSizeOfFilesInDir(tempDirectory);
    }
    return size;
  }

  static Future<void> requestPermission(FileSystemEntity file) async {
    PermissionStatus status = await Permission.storage.status;
  }

  ///循环获取缓存大小
  static Future<double> getTotalSizeOfFilesInDir(
      final FileSystemEntity file) async {
    if (file is File) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      double total = 0;
      for (final FileSystemEntity child in children) {
        total += await getTotalSizeOfFilesInDir(child);
      }
      return total;
    }
    return 0;
  }


  ///格式化文件大小
  static String formatSize(double value) {
    List<String> unitArr = ['B', 'K', 'M', 'G'];
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }

  ///删除文件夹下所有文件、或者单一文件
  static Future<void> deleteDirectory(FileSystemEntity file) async {
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      for (final FileSystemEntity child in children) {
        await deleteDirectory(child);
        await child.delete();
      }
    }
  }

  /// 删除部分文件夹缓存
  static void clearApplicationCache() async {
    Directory docDirectory = await getApplicationDocumentsDirectory();
    Directory tempDirectory = await getTemporaryDirectory();

    if (docDirectory.existsSync()) {
      await deleteDirectory(docDirectory);
    }

    if (tempDirectory.existsSync()) {
      await deleteDirectory(tempDirectory);
    }
  }

}